

var path = require('path')
var routerApi = require('../../utils/routeString.js')(__filename, __dirname);
var utils = require('../../utils/index.js')
var validate = utils.validate;
var SqlHelper = utils.SqlHelper;
var jwt = require('../../utils/jwt.js')
var dateHelper = require('../../utils/date.js')
var Queue = require('../../utils/Queue.js')

const startDate = new Date("2018.1.29");
const endDate = new Date("2018.2.21");

const reward1 = "定制帆布购物袋";
const reward1Num = 30;
// const reward1Num = 2;

const reward2 = "定制抱枕";
const reward2Num = 10;
// const reward2Num = 2;

const reward3 = "精美指甲钳";
const reward3Num = 150;
// const reward3Num = 2;

const rewardList = [reward1, reward2, reward3];
const rewardNumList = [reward1Num, reward2Num, reward3Num];

var cj = async function (params, fnOver) {
    var req = params.req;
    var res = params.res;

    var body = req.body || req.query;

    // 命令解析
    if (!body.token) {
        fnOver();
        return res.send({ code: 0, msg: '无效请求, token error' });
    }

    // 活动时间确认
    var nowDate = new Date();
    if (nowDate < startDate || nowDate >= endDate) {
        fnOver();
        return res.send({ code: 1, msg: '活动还未开始，请在2018.1.29至2018.2.21参与。' });
    }

    // 授权确认
    var tokenData = await jwt.decode(body.token);
    if (!tokenData || !tokenData.userid) {
        fnOver();
        return res.send({ code: 0, msg: '服务器忙...1002' });
    }

    // 是否已经中奖判断
    var sqlHelper = new SqlHelper('scatls_zpgame_180121');
    var result1 = await sqlHelper.asyncSelect({ openid: tokenData.userid });
    if (result1.length > 0) {
        if (typeof result1[0].reward == "string" && result1[0].reward.length > 0) {
            fnOver();
            // console.log(" 已经中奖 ");
            return res.send({ code: 2, msg: '您已经获得礼品了，请下次再来！' });
        }
    }

    // 判断今日是否已经发放完数据
    var randN = Math.floor(Math.random() * 3);
    var res2 = await sqlHelper.asyncSelect({ reward: rewardList[randN], getdate: dateHelper.now1() });
    if (res2.length >= rewardNumList[randN]) {
        fnOver();
        return res.send({ code: 3, msg: '真遗憾，明日还可以继续来哦~' });
    }

    // 发送奖励
    if (result1.length > 0) { // 参与过
        var res3 = await sqlHelper.asyncUpdate({ openid: tokenData.userid }, { reward: rewardList[randN], getdate: dateHelper.now1() });
        fnOver();
        return res.send({ code: 4, reward: rewardList[randN], msg: '恭喜您获得礼品' });
    } else { // 未参与过
        let data = {
            openid: tokenData.userid,
            reward: rewardList[randN],
            getdate: dateHelper.now1()
        }
        var res4 = await sqlHelper.asyncInsert(data);
        fnOver();
        return res.send({ code: 4, reward: rewardList[randN], msg: '恭喜您获得礼品' });
    }

    fnOver();
    return res.send({ code: 0,  msg: '系统错误' });
    console.log(" 逻辑结束 ");
}

var dj = async function (req, res) {
    var body = req.body || req.query;

    if (!body.token) {
        return res.send({ code: 0, msg: '无效请求, token error' });
    }

    // 授权确认
    var tokenData = await jwt.decode(body.token);
    if (!tokenData || !tokenData.userid) {
        return res.send({ code: 0, msg: '服务器忙...1002' });
    }

    if (!validate.isName(body.name) || !validate.isPhone(body.phone)) {
        return res.send({ code: 0, msg: '请填写正确的电话和姓名' });
    }

    var sqlHelper = new SqlHelper('scatls_zpgame_180121');
    var result1 = await sqlHelper.asyncUpdate({ openid: tokenData.userid }, { name: body.name, phone: body.phone });

    return res.send({ code: 5, msg: '登记成功' });
}

var getuserdata = async function (req, res) {
    var body = req.body || req.query;

    if (!body.token) {
        return res.send({ code: 0, msg: '无效请求, token error' });
    }

    // 授权确认
    var tokenData = await jwt.decode(body.token);
    if (!tokenData || !tokenData.userid) {
        return res.send({ code: 0, msg: '服务器忙...1002' });
    }

    var sqlHelper = new SqlHelper('scatls_zpgame_180121');
    var userdata = await sqlHelper.asyncSelect({ openid: tokenData.userid });

    return res.send({ code: 1, userdata: userdata[0] });
}

var q = new Queue();

// 改变领取状态
var changeState = async function (req, res, next) {
    var body = req.body || req.query;

    if (!body.token) {
        return res.send({ code: 0, msg: '账号密码错误' });
    }

    if (!body.openid) {
        return res.send({ code: 0, msg: '请指定openid.' });
    }

    try {
        var userid = await jwt.decode(body.token);
        var sqlHelper = new SqlHelper('scatls_zpgame_180121');
        var result = await sqlHelper.asyncUpdate({ openid: body.openid }, { state: "已经领取" });
        return res.send({ code: 1, msg: '更新成功' });
    } catch (error) {
        return res.send({ code: 0, msg: error.message });
    }

}

var login = async function (req, res, next) {
    var body = req.body || req.query;

    if (!body.account || !body.password) {
        return res.send({ code: 0, msg: '请输入您的账号和密码' });
    }

    if (body.account === "admin" && body.password === "matrixpassword2017") {
        var jwtData = await jwt.encode2(body.account);
        return res.send({ code: 1, token: jwtData.token });
    } else {
        return res.send({ code: 0, msg: '账号密码错误' });
    }

}

// return {list, count, comments}
var getTableData = async function (req, res) {
    var body = req.body || req.query;

    if (!body.token) {
        return res.send({ code: 0, msg: '账号密码错误' });
    }

    try {
        var userid = await jwt.decode(body.token);
        var sqlHelper = new SqlHelper('scatls_zpgame_180121');
        var result = await sqlHelper.asyncSelect(null, body.offset, body.limit);
        var result2 = await sqlHelper.asyncCount() //results[0].num
        var comments = await sqlHelper.asyncComments();
        return res.send({ code: 1, result: { list: result, count: result2[0].num, comments: comments } });
    } catch (error) {
        return res.send({ code: 0, msg: error.message });
    }

}


var analysisFn = function (req, res, next) {
    var body = req.body || req.query;

    var cmd = body.cmd;

    // 命令解析
    if (!cmd) {
        return res.send({ code: 0, msg: '无效请求, cmd参数出错' });
    }

    switch (cmd) {
        case 'cj':  // 抽奖
            q.addRequest({ req: req, res: res }, cj)
            break;
        case 'dj':
            dj(req, res);  // 登记
            break;
        case 'getuserdata':
            getuserdata(req, res);  // 获取用户数据
            break;
        case "login":
            login(req, res, next);
            break;
        case "getTableData":
            getTableData(req, res);
            break;
        case "changeState":
            changeState(req, res);
            break;
        default:
            return res.send({ code: 0, msg: '无效请求, cmd参数出错' });
    }
}

server.post({ path: routerApi, name: routerApi }, analysisFn)